package com.enba.mallapi.module.auth.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.enba.boot.core.enums.YesOrNoEnum;
import com.enba.boot.core.exception.BizException;
import com.enba.boot.core.utils.TreeNode;
import com.enba.boot.core.utils.TreeUtils;
import com.enba.mallapi.enums.OrgTypeEnum;
import com.enba.mallapi.module.auth.controller.req.OrgAddUpdateReq;
import com.enba.mallapi.module.auth.controller.resp.OrgTreeNodeResp;
import com.enba.mallapi.module.auth.controller.resp.OrgTreeTableNodeResp;
import com.enba.mallapi.module.auth.entity.Org;
import com.enba.mallapi.module.auth.mapper.OrgMapper;
import com.enba.mallapi.module.auth.service.IOrgService;
import com.enba.mallapi.utils.CodeGenerator;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户组织表 服务实现类
 *
 * @author 恩爸编程
 * @since 2025-02-28
 */
@Service
public class OrgServiceImpl extends ServiceImpl<OrgMapper, Org> implements IOrgService {

  @Autowired private CodeGenerator codeGenerator;

  @Override
  public List<TreeNode> getAllOrg() {

    return TreeUtils.<Org>buildTree(
        () ->
            this.getBaseMapper()
                .selectList(
                    Wrappers.<Org>lambdaQuery().eq(Org::getDeleted, YesOrNoEnum.NO.getCode())),
        (orgList) ->
            orgList.stream()
                .map(
                    e -> {
                      OrgTreeNodeResp orgTreeNodeResp =
                          new OrgTreeNodeResp(e.getId(), e.getParentId(), e.getOrgName());
                      orgTreeNodeResp.setOrgCode(e.getOrgCode());
                      orgTreeNodeResp.setOrgName(e.getOrgName());
                      orgTreeNodeResp.setOrgPath(e.getOrgPath());
                      orgTreeNodeResp.setParentId(e.getParentId());
                      orgTreeNodeResp.setParentCode(e.getParentCode());
                      orgTreeNodeResp.setOrgType(e.getOrgType());

                      return orgTreeNodeResp;
                    })
                .collect(Collectors.toList()));
  }

  @Override
  public List<TreeNode> getAllTreeTableOrg() {
    List<Org> orgList =
        this.getBaseMapper()
            .selectList(Wrappers.<Org>lambdaQuery().eq(Org::getDeleted, YesOrNoEnum.NO.getCode()));

    List<OrgTreeTableNodeResp> orgTreeTableNodeRespList = getOrgTreeTableNodeResp(orgList);

    // 返回树节点
    return TreeUtils.buildTree(orgTreeTableNodeRespList);
  }

  private List<OrgTreeTableNodeResp> getOrgTreeTableNodeResp(List<Org> orgList) {
    return orgList.stream()
        .map(
            e -> {
              OrgTreeTableNodeResp orgTreeNodeResp =
                  new OrgTreeTableNodeResp(e.getId(), e.getParentId(), e.getOrgName());
              orgTreeNodeResp.setOrgCode(e.getOrgCode());
              orgTreeNodeResp.setOrgName(e.getOrgName());
              orgTreeNodeResp.setOrgPath(e.getOrgPath());
              orgTreeNodeResp.setParentId(e.getParentId());
              orgTreeNodeResp.setParentCode(e.getParentCode());
              orgTreeNodeResp.setOrgType(e.getOrgType());
              orgTreeNodeResp.setStatus(e.getStatus());
              orgTreeNodeResp.setCreateTime(e.getCreateTime());

              return orgTreeNodeResp;
            })
        .collect(Collectors.toList());
  }

  @Transactional(rollbackFor = Exception.class)
  @Override
  public boolean saveOrUpdate(OrgAddUpdateReq req) {
    if (req.getId() == null) {
      // 新增节点
      Org org = new Org();
      org.setOrgCode(codeGenerator.orgGenerateCode());
      org.setOrgName(req.getOrgName());
      org.setParentId(req.getParentId());
      org.setStatus(req.getStatus());

      Long parentId = req.getParentId();
      if (parentId == 0L) {
        // 新增集团顶级节点
        org.setParentCode("0");
        org.setOrgType(OrgTypeEnum.JT.getCode());
        // 临时占位
        org.setOrgPath("-1");
      } else {
        // 新增公司或者部门节点
        Org parentOrg = this.getById(parentId);
        if (parentOrg == null) {
          BizException.throwEx("父级组织不存在");
        }

        if (OrgTypeEnum.JT.getCode().equals(parentOrg.getOrgType())) {
          // 新增公司节点
          org.setParentCode(parentOrg.getOrgCode());
          org.setOrgType(OrgTypeEnum.GS.getCode());
          // 临时占位
          org.setOrgPath("-1");
        } else if (OrgTypeEnum.GS.getCode().equals(parentOrg.getOrgType())) {
          // 新增部门节点
          org.setParentCode(parentOrg.getOrgCode());
          org.setOrgType(OrgTypeEnum.BM.getCode());
          // 临时占位
          org.setOrgPath("-1");
        } else if (OrgTypeEnum.BM.getCode().equals(parentOrg.getOrgType())) {
          BizException.throwEx("部门下禁止新建组织");
        }
      }

      boolean save = this.save(org);
      if (save) {
        // 更新组织机构路径
        if (parentId == 0L) {
          org.setOrgPath(org.getId() + ",");
        } else {
          Org parentOrg = this.getById(parentId);
          org.setOrgPath(parentOrg.getOrgPath() + org.getId() + ",");
        }
      }

      return this.updateById(org);
    } else {
      // 编辑节点（只能更改名称和状态!!!）
      return this.getBaseMapper()
              .update(
                  Wrappers.<Org>lambdaUpdate()
                      .set(Org::getOrgName, req.getOrgName())
                      .set(Org::getStatus, req.getStatus())
                      .eq(Org::getId, req.getId()))
          > 0;
    }
  }
}
